package com.imay.live.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.util.FileUtil;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.cocos.IMayCocos;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.fragment.LiveEndFragment;
import com.imay.live.fragment.room.LinkMicInviteFragment;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.ShareSDKHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.manager.SensitiveWordFilterManager;
import com.imay.live.manager.UnreadManager;
import com.imay.live.manager.UploadFileManager;
import com.imay.live.media.LivePusher;
import com.imay.live.model.UserInfoModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.proto.helper.ProtoSocketFactory;
import com.imay.live.proto.room.RoomEndLiveResp;
import com.imay.live.proto.room.RoomGetMyLiveInfoResp;
import com.imay.live.proto.room.RoomStartLiveResp;
import com.imay.live.proto.room.RoomStatInfo;
import com.imay.live.proto.room.StreamInfoResp;
import com.imay.live.proto.user.UserInfoCard;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.custom.RoomBaseView;
import com.imay.live.view.custom.RoomPushNormalView;
import com.imay.live.view.custom.StartLiveNormalView;
import com.imay.live.view.custom.StartLiveView;
import com.imay.live.R;
import com.imay.photopicker.PhotoPicker;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.List;

/**
 * Created by jeaman on 2017/3/17.
 */

public class RoomPushNormalActivity extends RoomPushBaseActivity implements StartLiveNormalView.OnNormalActionClickListener, RoomPushNormalView.OnPushActionListener, LivePusher.PushEventListener {

    private final static String TAG = RoomPushNormalActivity.class.getSimpleName();

    private boolean mRequestLiveSuggestSuccess; //是否成功获取标签

    //请求开播信息和推流地址成功了才允许开播
    private boolean mRequestLiveInfoSuccess;    //请求开播信息是否成功
    private boolean mRequestPushUrlSuccess; //请求推流地址是否成功

    //请求command
    private String mCommandMyLiveInfo;
    private String mCommandPushUrl;
    private String mCommandStartLive;
    private String mCommandEndLive;
    private String mCommandLiveSuggestList;
    private boolean hasDiconnect;

    public static void startActivity(Context content) {
        Intent intent = new Intent(content, RoomPushNormalActivity.class);
        content.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_push;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        initRoomView();
        addRoomView(0);
        getRoomView().hideAllViewWithoutCocos();

        requestMyLiveInfo();    //获取开播信息
        requestPushUrl();   //获取推流地址
        requestLiveSuggestList();   //获取开播标签
        mLivePusher.setPushEventListener(this);
    }

    private StartLiveNormalView getStartLiveView() {
        return (StartLiveNormalView) mStartLiveView;
    }

    @Override
    protected StartLiveView createStartLiveView() {
        StartLiveNormalView startLiveNormalView = new StartLiveNormalView(this);
        startLiveNormalView.setOnNormalActionClickListener(this);
        return startLiveNormalView;
    }

    @Override
    protected RoomBaseView createRoomView() {
        //创建对应的 view并设置listener
        RoomPushNormalView roomView = new RoomPushNormalView(this);
        roomView.setOnPushActionListener(this);
        return roomView;
    }

    @Override
    protected int getWatermark() {
        return R.mipmap.shuiyin540;
    }

    private RoomPushNormalView getRoomView() {
        return (RoomPushNormalView) mRoomView;
    }

    @Override
    protected void requestStartLive() {
        String title = getStartLiveView().getTitle();
        if (SensitiveWordFilterManager.getInstance().hasSensitiveWord(title)) {
            ToastUtil.show(this, R.string.live_sensitive_title);
        } else {
            requestStartLive(title, getStartLiveView().getTagList());
        }
    }

    //结束直播
    @Override
    protected void requestEndLive() {
        cocosExitRoom();
        stopPublishRtmp();
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), null);
        mCommandEndLive = ProtoRequestHelper.task(ProtoSocketFactory.requestEndLive()).request(this);
    }

    @Override
    protected void onLocationSuccess() {
        if (mShowLocation && mStartPush) {
            ProtoRequestHelper.task(ProtoSocketFactory.requestSetCity(mCity, mLatitude, mLongitude)).request(this);
        }
    }

    @Override
    protected void setLinkMicNumber(int number) {
        if (getRoomView() != null) {
            getRoomView().setLinkMicNumber(number);
        }
    }

    @Override
    public void onBackPressed() {
        if (mStartPush && !mShowExitConfirm) {
            DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), null, getString(R.string.live_push_end_dialog_message), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mShowExitConfirm = true;
                    requestEndLive();
                }
            });
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void cocosExitRoomByType() {
        IMayCocos.exitRoomByPush(getRoomId());
    }

    private void processEndLive(String data) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        if (data != null) {
            RoomEndLiveResp resp = JSON.parseObject(data, RoomEndLiveResp.class);
            if (resp.result == ResultCode.CodeSuccess && resp.info != null) {
                showEndLive(resp.info);
            } else {
                showEndLive(null);
            }
        } else {
            showEndLive(null);
        }
    }

    //获取开播信息，获取成功才允许开播
    private void requestMyLiveInfo() {
        mCommandMyLiveInfo = ProtoRequestHelper.task(ProtoSocketFactory.requestMyLiveInfo()).request(this);
    }

    private void processMyLiveInfo(String data) {
        RoomGetMyLiveInfoResp resp = JSON.parseObject(data, RoomGetMyLiveInfoResp.class);
        if (resp.result == ResultCode.CodeSuccess) {
            mRequestLiveInfoSuccess = true;
            if (!TextUtils.isEmpty(resp.imgFace)) {
                mLastCoverUrl = resp.imgFace;
                getStartLiveView().setCoverImageUrl(resp.imgFace);
            } else {
                getStartLiveView().showCoverTip();
            }
            setStartEnabled();
        }
    }

    //获取推流地址
    private void requestPushUrl() {
        mCommandPushUrl = ProtoRequestHelper.task(ProtoHttpFactory.requestPushUrl()).request(this);
    }

    private void processPushUrl(String data) {
        Result<StreamInfoResp> result = JSON.parseObject(data, new TypeReference<Result<StreamInfoResp>>() {}.getType());
        if (result.result == ResultCode.CodeSuccess && result.data != null) {
            mRequestPushUrlSuccess = true;
            setPushUrl(result.data.getPushStreamUrl());
            setStartEnabled();
        } else {
            ErrorResult.toastError(RoomPushNormalActivity.this, result.result);
        }
    }

    //允许开播
    private void setStartEnabled() {
        getStartLiveView().setStartEnabled(mRequestPushUrlSuccess && mRequestLiveInfoSuccess);
    }

    //请求开播
    private void requestStartLive(String title, List<String> tags) {
        String city = null;
        double latitude = 0;
        double longitude = 0;
        if (mShowLocation) {
            city = mCity;
            latitude = mLatitude;
            longitude = mLongitude;
        }
        mCommandStartLive = ProtoRequestHelper.task(ProtoSocketFactory.requestStartLive(title, mCoverUrl, city, latitude, longitude, tags)).request(this);
    }

    private void processStartLive(String data) {
        RoomStartLiveResp resp = JSON.parseObject(data, RoomStartLiveResp.class);
        if (resp.result == ResultCode.CodeSuccess) {
            startLive(resp.roomId, resp.hostesInfo);
            IMayCocos.enterRoomByPush(resp.roomId, data);    //注意：先添加cocos才能调用cocos的方法
            requestRoomTips();
            //清除召唤红点
            UnreadManager.getInstance().postUnreadEvent(UnreadManager.TYPE_UNREAD_CALL_LIVE_PROFILE,0);
        } else {
            ErrorResult.toastError(RoomPushNormalActivity.this, resp.result);
        }
    }

    protected void startLive(long roomId, UserInfoCard userInfoCard) {
        setRoomId(roomId);
        setAnchorInfo(userInfoCard);

        removeStartLiveView();
        setRoomAnchorInfo();
        getRoomView().showAllView();

        startPublishRtmp();
    }

    private void showEndLive(RoomStatInfo roomStatInfo) {
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), LiveEndFragment.newInstance(roomStatInfo));
    }

    //开播标签
    private void requestLiveSuggestList() {
        if (mRequestLiveSuggestSuccess) {
            return;
        }
        mCommandLiveSuggestList = ProtoRequestHelper.task(ProtoHttpFactory.requestLiveSuggest()).request(this);
    }

    private void processLiveSuggestList(String data) {
        Result<List<String>> result = JSON.parseObject(data, new TypeReference<Result<List<String>>>() {}.getType());
        if (result.result == ResultCode.CodeSuccess) {
            mRequestLiveSuggestSuccess = true;
            if (getStartLiveView() != null) {
                getStartLiveView().setTagList(result.data);
            }
        }
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        if (command.equals(mCommandMyLiveInfo)) {   //开播信息
            processMyLiveInfo(data);
        } else if (command.equals(mCommandPushUrl)) {   //获取推流地址
            processPushUrl(data);
        } else if (command.equals(mCommandStartLive)) { //开始直播
            processStartLive(data);
        } else if (command.equals(mCommandEndLive)) {   //结束直播
            processEndLive(data);
        } else if (command.equals(mCommandLiveSuggestList)) {  //获取开播标签列表
            processLiveSuggestList(data);
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        if (command.equals(mCommandEndLive)) {   //结束直播
            processEndLive(null);
        } else if (command.equals(mCommandStartLive)) {
            if (code == ResultCode.CodeUserRealNameVerifiedNotExist || code == ResultCode.CodeUserRealNameVerifieding) {    //未实名认证
                needRealNameAuth();
            }
        } else {
            ErrorResult.toastError(RoomPushNormalActivity.this, code);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (getStartLiveView() != null) {  //点击隐藏开播图气泡
                getStartLiveView().hideCoverTip();
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onAddTagClick() {
        requestLiveSuggestList();
    }

    @Override
    public void onAddCoverClick() {
        PhotoPicker.builder()
                .setPhotoCount(9)
                .setGridColumnCount(3)
                .start(this);
    }

    @Override
    public void onStartShareClick(SHARE_MEDIA shareMedia) {
        //开播分享
        UserInfoModel user = UserInfoCache.getUserInfo();
        if (user == null) {
            Log.e(TAG, "share error: no user info!");
        } else {
            String roomTitle = getStartLiveView().getTitle();
            String nick = user.getUser().getNick();
            String avatar = user.getUser().getImgHead();
            long roomId = user.getUser().getRoomId();
            String image = mCoverUrl != null ? mCoverUrl : (mLastCoverUrl != null ? mLastCoverUrl : avatar);
            String url = UrlHelper.getShareLiveUrl(roomId);
            String title = TextUtils.isEmpty(roomTitle) ? getString(R.string.live_share_title, nick) : roomTitle;
            String des = getString(R.string.live_share_des, nick);
            ShareSDKHelper.getBuilder(this, shareMedia).share(url,title,des,image);
        }
    }

    @Override
    public void onLicenseClick() {
        WebViewActivity.startActivity(this, UrlHelper.LIVE_LICENSE);
    }

    private void cropCover(String filePath) {
        File file = ICUtils.getOutputMediaFile(this);
        UCrop.Options options = new UCrop.Options();
        options.setToolbarColor(Color.BLACK);
        options.setActiveWidgetColor(Color.BLACK);
        options.setStatusBarColor(Color.BLACK);
        options.setHideBottomControls(true);
        UCrop.of(Uri.fromFile(new File(filePath)), Uri.fromFile(file))
                .withOptions(options)
                .withAspectRatio(9, 16)
                .withMaxResultSize(1080, 1920)
                .start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PhotoPicker.REQUEST_CODE:
                    Bundle bundle = data.getExtras();
                    String path = bundle.getString("filePath");
                    cropCover(path);
                    break;
                case UCrop.REQUEST_CROP:
                    final Uri resultUri = UCrop.getOutput(data);
                    if (resultUri != null) {
                        if (getStartLiveView() != null) {
                            getStartLiveView().hideCoverTip();
                            getStartLiveView().setCoverImage(resultUri);
                        }
                        mCoverUrl = UploadFileManager.getInstance().uploadPic(resultUri.getPath(), new UploadFileManager.UploadCallBack() {

                            @Override
                            public void uploadSuccess(String fileUrl) {
                                if (mStartPush && !isFinishing()) {   //TODO 上传，未处理上传进度等
                                    ProtoRequestHelper.task(ProtoSocketFactory.requestSetCover(mCoverUrl)).request(null);
                                }
                                FileUtil.deleteFile(resultUri.getPath());
                            }

                            @Override
                            public void uploadFailer(int errorCode, String errorMessage) {
                                FileUtil.deleteFile(resultUri.getPath());
                            }
                        });

                    }
                    break;
            }
        }
    }

    @Override
    public void onLinkMicClick() {
        //主播端，连麦用户列表
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), LinkMicInviteFragment.newInstance(mRoomId));
    }

    @Override
    public void onGameClick() {
        showGame();
    }

    @Override
    public void onGiftClick() {
        onCocosChooseUserClick();
    }

    @Override
    public void onScreenShotClick() {
        screenShot(SCREENSHOT_SHARE);
    }

    @Override
    public void onShareClick() {
        shareRoom();
    }

    @Override
    public void onCameraClick() {
        switchCamera();
    }

    @Override
    public void onBeautyClick() {
        showBeautyView();
    }

    @Override
    public void onBGMClick() {

    }

    @Override
    public void onDisconnet() {
        hasDiconnect = true;
    }

    @Override
    public void onRestartPush() {
        if (hasDiconnect){
            ProtoRequestHelper.task(ProtoSocketFactory.requestResumePush()).request(null);
            hasDiconnect = false;
        }

    }

    @Override
    public void onUserHeadClick(UserInfoCard userInfoCard) {

    }
}
